package com.bean.activiti.util;

import com.bean.activiti.entity.*;
import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.identity.Group;
import org.activiti.engine.impl.persistence.entity.GroupEntity;
import org.activiti.engine.impl.persistence.entity.UserEntity;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * activiti中使用得到的工具方法
 * @author Gavin Lee
 * @version 1.0
 * @date 2020-09-18 12:26
 * @desc
 */
public class ActivitiUtil {

    /**
     * 将历史参数列表设置到实体中去
     * @param entity 实体
     * @param varInstanceList 历史参数列表
     */
    public static <T> void setVars(T entity, List<HistoricVariableInstance> varInstanceList) {
        Class<?> tClass = entity.getClass();
        try {
            for (HistoricVariableInstance varInstance : varInstanceList) {
//                Field field = tClass.getDeclaredField(varInstance.getVariableName());
                Field field = Arrays.asList(tClass.getDeclaredFields()).stream().filter(field1 -> field1.getName().equalsIgnoreCase(varInstance.getVariableName())).count() > 0 ?
                        tClass.getDeclaredField(varInstance.getVariableName()): null;
                if (field == null) {
                    continue;
                }
                field.setAccessible(true);
                field.set(entity, varInstance.getValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static UserEntity toActivitiUser(SysUser bUser){
        ActivitiUser userEntity = new ActivitiUser();
        userEntity.setSysUser(bUser);
        return userEntity;
    }

    public static GroupEntity toActivitiGroup(SysRole sysRole){
        ActivitiGroup groupEntity = new ActivitiGroup();
        groupEntity.setSysRole(sysRole);
        return groupEntity;
    }


    public static List<Group> toActivitiGroups(List<SysRole> sysRoles){
        List<Group> groups = new ArrayList<Group>();
        for (SysRole sysRole : sysRoles) {
            GroupEntity groupEntity = toActivitiGroup(sysRole);
            groups.add(groupEntity);
        }
        return groups;
    }

    /**
     *
     * @param hisInstance
     * @param historyService
     * @return
     */
    public static Vacation historicProcessInstanceToVacation(HistoricProcessInstance hisInstance, HistoryService historyService) {
        Vacation vacation = new Vacation();
        vacation.setApplyUser(hisInstance.getStartUserId());
        vacation.setApplyStatus("申请结束");
        vacation.setApplyTime(hisInstance.getStartTime());
        List<HistoricVariableInstance> varInstanceList = historyService.createHistoricVariableInstanceQuery()
                .processInstanceId(hisInstance.getId()).list();
        ActivitiUtil.setVars(vacation, varInstanceList);
        return vacation;
    }
}
